﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

namespace ShootMan
{
    //游戏客户端开启入口类
    public class GameStartEntry : MonoBehaviour
    {
        [SerializeField]
#if UNITY_EDITOR
        public bool _onlineMode = false;
#else
        public bool _onlineMode = true;
#endif

        [SerializeField]
        private string _updateUrl = "";

        [SerializeField]
        private GameObject _objLoadProgressRoot = null;

        [SerializeField]
        private Image _imageLoadProgress = null;

        [SerializeField]
        private Text _textProgressPercent = null;

        [SerializeField]
        private Text _textDownloadSpeed = null;

        void Awake()
        {
            shaco.SpriteAtlasHelper.Init();
        }

        void Start()
        {
            Debug.Log("GameStartEntry Start...");
            _objLoadProgressRoot.SetActive(true);
            StartCoroutine(DownloadCoroutine());
        }

        IEnumerator DownloadCoroutine()
        {            
            //基础代码已经替换完毕，等后续有空来测试下
            yield return DownloadWithPackage("DefaultPackage", _updateUrl, 0, 0.3f);
            yield return DownloadWithPackage("configs", _updateUrl, 0.3f, 0.4f);
            yield return DownloadWithPackage("scripts", _updateUrl, 0.4f, 0.6f);
            yield return DownloadWithPackage("audio", _updateUrl, 0.6f, 0.8f);
            yield return LoadGameDll();
            yield return StartGame();
        }

        IEnumerator DownloadWithPackage(string packageName, string prefixURL, float startPercent, float endPercent)
        {
            var updater = new shaco.YooAssetPackageUpdater();

            updater.onDownloadProgressCallback = (float percent, string descryption) =>
            {
                OnDownloadingCallBack(startPercent, endPercent, percent, descryption);
            };

            updater.onDownloadErrorCallback = error =>
            {
                Debug.LogError($"下载资源包[{packageName}] 发生错误: {error}");
            };

            if (_onlineMode)
            {
                var url = $"{prefixURL}/{packageName}";
                yield return updater.StartWithHostPlayMode(url, url, packageName);
            }
            else
                yield return updater.StartWithEditorSimulateMode(packageName);
        }
        
        void OnDownloadingCallBack(float startPercent, float endPercent, float percent, string descryption)
        {
            //下载进度
            percent = (endPercent - startPercent) * percent + startPercent;
            _imageLoadProgress.fillAmount = percent;
            _textProgressPercent.text = (percent * 100.0f) + "%";

            //下载详情信息
            _textDownloadSpeed.text = descryption;
        }

        IEnumerator LoadGameDll()
        {
            Debug.Log("LoadGameDll start...");
            var hybridHotUpdateDllNames = new string[]
            {
                "Assembly-shaco-CSharp.dll",
                "Assembly-shaco-Unity.dll",
                "Assembly-DebugWindow.dll",
                "Assembly-ShootMan.dll",
                "Assembly-YooAssetResource.dll",
            };
            yield return shaco.HyridCLRHelper.LoadDll(hybridHotUpdateDllNames, "scripts", $"Assets/ShootMan/Resources_HotUpdate/ScriptsDll", "game dll", (name, bytes) =>
            {
                Debug.Log($"LoadGameDll:{name}");
                try
                {
                    System.Reflection.Assembly.Load(bytes);
                }
                catch (System.Exception ex)
                {
                    Debug.LogError($"LoadGameDll error:{name}, e=" + ex);
                }
            });
            Debug.Log("LoadGameDll end...");
        }

        private IEnumerator StartGame()
        {
            Debug.Log("StartGame....1");
            YooAsset.YooAssets.SetDefaultPackage(YooAsset.YooAssets.GetPackage("DefaultPackage"));
            var load = YooAsset.YooAssets.LoadAssetAsync<GameObject>($"Assets/ShootMan/Resources_HotUpdate/Prefabs/UI/GameEntry.prefab");
            while (!load.IsDone)
            {
                OnDownloadingCallBack(load.Progress, 0.8f, 0.9f, "");
                yield return null;
            }
            Debug.Log("StartGame....2");
            MonoBehaviour.Instantiate(load.AssetObject as GameObject);
            MonoBehaviour.Destroy(this.gameObject);
        }
    }
}